package com.cskaoyan.market.controller;


import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.service.AdminStorageService;
import com.cskaoyan.market.service.impl.AdminStorageServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @description: 存储对象管理
 * @author: 刘国兴
 **/
@WebServlet("/admin/storage/*")
@MultipartConfig
public class AdminStorageController extends HttpServlet {

    private String basePath="D:\\image";

    private AdminStorageService storageService = new AdminStorageServiceImpl();

    @Override

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        dispatchRequest(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        dispatchRequest(req, resp);
    }

    /**
     * @author 刘国兴
     * @description 分发链接
     */
    private void dispatchRequest(HttpServletRequest req, HttpServletResponse resp) {
        String op = req.getPathInfo();
        try {
            switch (op) {
                case "/list":
                    //列表显示与查询功能
                    getStorageList(req, resp);
                    break;
                case "/update":
                    //编辑对象
                    updateStorage(req, resp);
                    break;
                case "/delete":
                    //删除对象
                    deleteStorage(req, resp);
                    break;
                case "/create":
                    //上传图片
                    createStorage(req,resp);
                    break;
                default:
                    //重定向交给其他servlet处理这个请求
                    resp.sendRedirect(req.getRequestURI());
            }
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }
    }

    /**
     * @author 刘国兴
     * @description 获取存储对象列表
     */
    private void getStorageList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //第一步：获取req中&连接的参数page&limit&username&sort&order
        Map<String, String[]> parameterMap = req.getParameterMap();
        //第二步：调用service处理业务，并把参数传递下去，获取storageList
        List<MarketStorage> StorageList = storageService.list(parameterMap);
        //第三步：处理成标准响应的格式然后响应回去
        Object okList = ResponseUtil.okList(StorageList);
        resp.getWriter().println(JacksonUtil.writeValueAsString(okList));
    }

    /**
     * @author 刘国兴
     * @description 更新存储对象信息
     */
    private void updateStorage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取req中的json字符串
        String reqJson = req.getReader().readLine();
        //调用service处理业务
        String respJson = storageService.update(reqJson);
        //响应
        resp.getWriter().println(respJson);
    }

    /**
     * @author 刘国兴
     * @description 删除存储对象
     */
    private void deleteStorage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取req中的json字符串
        String reqJson = req.getReader().readLine();
        //调用service处理业务
        String respJson = storageService.delete(reqJson);
        //响应
        resp.getWriter().println(respJson);
    }

    /**
     * @author 王鸣纯
     * @description 上传文件
     */
    private void createStorage(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Part part = req.getPart("file");
        String name = part.getSubmittedFileName();
        String key= UUID.randomUUID().toString() + name.substring(name.indexOf("."));
        int size = (int) part.getSize();
        String type = part.getContentType();
        String url="/wx/storage/fetch/"+key;
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(key);
        marketStorage.setName(name);
        marketStorage.setType(type);
        marketStorage.setSize(size);
        marketStorage.setUrl(url);
        marketStorage.setAddTime(LocalDateTime.now());
        marketStorage.setUpdateTime(LocalDateTime.now());
        // 执行文件上传，存储到对应位置
        part.write(basePath+"/"+key);
        // 写入数据库
        storageService.insert(marketStorage);
        // 注意：url一定要携带主机、端口号，如果/xxxx会默认拼接localhost：9527
        url="http://localhost:8083"+url;
        marketStorage.setUrl(url);
        Object o = ResponseUtil.ok(marketStorage);
        resp.getWriter().println(JacksonUtil.writeValueAsString(o));
    }
}
